NOTE

1.3 MySQL SQL Tuning

These notes record SQL-tuning scenarios, starting with data volume and concurrency and examining changes such as limiting query ranges.

DatabasesCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. Single-Instance MySQL Bottleneck

3 million records, 2,000 concurrent requests

2. Overall Approach

3. Steps

3.1. Locate Slow Queries

3.2. Analyze SQL

3.3. Rewrite SQL

  1. Limit the range of data queried: for example, query only orders from the past month.
  2. Optimize paginated queries.
    • At the database level
      • For example, change select * from table where age > 20 limit 1000000,10 to select * from table where id in (select id from table where age > 20 limit 1000000,10). The core idea is the same: reduce the amount of data loaded.
    • Reduce demand for these queries through product requirements
      • Do not support jumping directly to a specific page millions of pages ahead. Allow only sequential browsing or navigation along a defined path.

4. Examples

4.1. Paginated Query Optimization

  • If there are 1 million records, retrieve the last 100,000.

4.1.1. limit offset

  • Traditional form: select * from xxx limit 10W offset 90W
  • It cannot use an index and needs to scan the whole table before retrieving the last 100,000.

4.1.2. limit id

  • select * from xxx where id in (select id from xxx limit 10W offset 90W)
  • It can use the ID index, but it still needs to scan the entire ID index.

4.1.3. Join Query

  • select * from xxx INNER JOIN( select id from xxx limit 10W, 90W) as a USING(id)

4.1.4. BETWEEN … AND

  • select * from xxx where id BETWEEN 90W AND 100W
  • It can use the ID index. If IDs are not continuous and auto-incrementing, this method is not feasible.

4.1.5. Maximum-ID Query Method

  • select * from xxx where id > 90W limit 10W
  • It can use the ID index.

4.2. Batch Update

Six Ways to Batch Update Data in MySQL - Juejin

4.3. Join Optimization

  • If the index of the driven table can be used, the join statement still has its advantages.
  • If the index of the driven table cannot be used, only the Block Nested-Loop Join algorithm can be used, so this kind of statement should be avoided as much as possible.
  • When using a join, the smaller table should be used as the driving table.
  • MySQL Table Access Methods.md

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub